package doc2db.interfaces.action.templates;

import doc2db.interfaces.action.*;
import doc2db.DbManager.DbSelects;
import doc2db.Keey;
import doc2db.UserProp;
import doc2db.fileWorker.FileBeginer;
import doc2db.fileWorker.FileIO;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.Properties;
import javax.swing.JEditorPane;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

/**
 *
 * @author yuriy
 */
public class ChoiceTemplAction extends CreateDialog implements ActionListener{
    protected Properties prop ;
    private String pswd;
    protected boolean neededPswd = false;

    private JTextArea tem;
    private JTextArea metTem;

    public ChoiceTemplAction(JEditorPane __p, JEditorPane t2) {
        super(__p, t2);        
    }
    
    public void setTextArea(JTextArea tm, JTextArea mtm){
        tem = tm;
        metTem = mtm;
    }

    @Override
    protected String [] initToolTipeText(Object s []){
        String [] retStr = null;
        String str = "SELECT about FROM " + prop.getProperty("dbTableName") + " ORDER BY id ;";
        
        DbSelects query = this.initDbSelects();
        if (query.sendQuery(str)) {
            int rows = query.getRows();
            retStr = new String[rows];
            for (int i = 1; i <= rows; i++) {
                StringBuilder toolFont = new StringBuilder();
                toolFont.append("<html>\n");
                toolFont.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/>\n");
                toolFont.append("<pre>\n");
                toolFont.append("<font size=\"3\">\n");
                String _s = this.minimString(query.getString(i, "about"),"\n",36, 70);
                toolFont.append(_s.replace("&", "&amp;").replace(">", "&gt;")
                        .replace("<", "&lt;").replace("\"", "&quot;").replace("'", "&apos;"));
                retStr[i - 1] = toolFont.toString();
            }
        }
        return retStr;
    }

    private String minimString(String isS, String delimiter, int kol, int kol2){
        String [] arr = isS.split(delimiter);
        StringBuilder ret = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            if (i == kol) {
                ret.append(" ...");
                break;
            }
            String s = "";
            if(arr[i].length()>kol2){
                s = arr[i].substring(0, kol2) + "...";
            }else{
                s = arr[i];
            }
            ret.append("").append(s).append(delimiter);
        }
        return ret.toString();
    }

    protected DbSelects initDbSelects(){
        DbSelects db = null;

        String port = "5432";
        StringBuilder url = new StringBuilder()
                .append("jdbc:postgresql://").append(prop.getProperty("dbHost")).append(":")
                .append(port).append("/").append(prop.getProperty("dbName"));

        if(neededPswd){
            
        } else {
            prop.setProperty("user", UserProp.userInDb);
        }
        prop.setProperty("password", pswd);
        try {
            db = new DbSelects(url.toString(), prop);
        } catch (SQLException ex) {
        } catch (ClassNotFoundException ex) {
        }

        return db;
    }

    @Override
    protected Object[] init(Object[] result) {
        String str = "SELECT * FROM " + prop.getProperty("dbTableName") + " ORDER BY id ;";
        DbSelects q = this.initDbSelects();
        if (q.sendQuery(str)) {
            int rows = q.getRows();
            result = new D[rows];
            for (int i = 1; i <= rows; i++) {
                result[i - 1] = new D("" + q.getString(i, "name"), q.getInt(i, "id"));
            }
        }
        return result;
    }
    
    protected boolean initAll(){
        prop = new Properties(new UserProp().getPropToTemplatesDb());
        if (!Boolean.parseBoolean(prop.getProperty("isAllProp"))) {
            JOptionPane.showMessageDialog(null, "Нет всех параметров базы\n",
                        "error", JOptionPane.ERROR_MESSAGE);
            return false;
        }
        if(neededPswd){
            pswd = JOptionPane.showInputDialog("Пароль БД с таблицами шабонов " +
                    "для пользователя "+ this.prop.getProperty("user"));
            if ((pswd != null) && (pswd.length() > 0)) {
            }else{
                return false;
            }

        } else {
            pswd = UserProp.pswdInDb;
        }

        DbSelects con = this.initDbSelects();
        if(con == null){
            JOptionPane.showMessageDialog(null, "Неудалось создать соеденение\n",
                        "error", JOptionPane.ERROR_MESSAGE);
                return false;
        }

        return true;
    }

    private void writeTemlatesInFiles(){
        int num = resNum;
        if (res instanceof ChoiceTemplAction.D){
            num = ((D)res).index;
        }
//        else {
//            System.err.println(res.getClass());
//            System.exit(1);
//        }

        String str2 = FileBeginer.resurse_users_usersFolder + Keey.sp + UserProp.user + Keey.sp;
        String str = "SELECT \"metaTemplates\", \"templates\" FROM " +
                prop.getProperty("dbTableName") + " WHERE name=\'" + res + "\' " +
                "AND id=\'" + num + "\' ;";
//        System.out.println(str);
        DbSelects query = this.initDbSelects();

        if (query.sendQuery(str)) {
            String metaTmpltData = query.getString(1, "metaTemplates");
            FileIO.createFile(metaTmpltData, str2 + FileBeginer.metaTemplatesName);
            if (metTem != null) {
                metTem.setText(metaTmpltData);
            }

            String tmpltData = query.getString(1, "templates");
            FileIO.createFile(tmpltData, str2 + FileBeginer.templatesName);
            if (tem != null) {
                tem.setText(tmpltData);
            }

//            System.out.println("metaTemplates");
//            System.out.println(metaTmpltData);
//            System.out.println("\ntemplates");
//            System.out.println(tmpltData);

            JOptionPane.showMessageDialog(null, "Шаблон выбран\n",
                    "doc2db: выбор шаблона", JOptionPane.INFORMATION_MESSAGE);
        }else{
            JOptionPane.showMessageDialog(null, 
                    "<html>Неудалось выполнить sql запрос\n" + str,
                    "doc2db: выбор шаблона", JOptionPane.INFORMATION_MESSAGE);
        }

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(! this.initAll()){
            return;
        }

        if (res.equals("__NULL")) {
            this.show();
        }
        if (res.equals("__NULL")) {
            return;
        }

        this.writeTemlatesInFiles();
        
        res = "__NULL";
        resNum = 0;
        
    }

    class D {
        final String string;
        final int index;

        public D(String string, int index) {
            this.string = string;
            this.index = index;
        }

        @Override
        public String toString() {
            return String.valueOf(string);
        }
    }

}
